﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using S.Breed.ApI.Application.Command;
using S.Breed.Domain;
using S.Breed.Domain.Dto;
using S.Breed.Infrastructure.Interface;
using S.Common.helper;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using static S.Breed.ApI.Application.Command.MaternalMatingCommand;
using System.Transactions;
using System.Xml;
using System.Linq;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
using Microsoft.Data.SqlClient;
using System.Data;
using Dapper;
using Authorization.Center.Dto;
using Org.BouncyCastle.Asn1.Ocsp;
using S.Common.EditReproductivePresenceStateHelper;

namespace S.Breed.ApI.Application.CommandHandlers
{
    public class MaternalMatingCommandHander : IRequestHandler<AddMaternalMatingCommand, int>,IRequestHandler<UpdateStateCommand,int>,IRequestHandler<UpdExamineCommand, bool>,IRequestHandler<UpdMaternalCommand,bool>,IRequestHandler<DelMaternalCommand,bool>,IRequestHandler<UpdateHuiStateCommand,int>
    {
        private readonly IMaternalMatingRepository maternalMating;
        private readonly IMapper mapper;
        private readonly IConfiguration configuration;
        private readonly IHttpContextAccessor httpContextAccessor;

        public MaternalMatingCommandHander(IMaternalMatingRepository maternalMating,IMapper mapper, IConfiguration configuration, IHttpContextAccessor httpContextAccessor)
        {
            this.maternalMating = maternalMating;
            this.mapper = mapper;
            this.configuration = configuration;
            this.httpContextAccessor = httpContextAccessor;
        }
        /// <summary>
        /// 配种新增
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<int> Handle(AddMaternalMatingCommand request, CancellationToken cancellationToken)
        {
            string Gateway = configuration.GetValue<string>("Gateway");
            using (var scope = new TransactionScope())
            {
                try
                {
                    List<MaternalMatingModel> maternalMatingModes = new List<MaternalMatingModel>();

                    foreach (var a in request.MaternalMatings)
                    {
                        MaternalMatingModel maternalMatingModel = new MaternalMatingModel()
                        {
                            UserId = request.UserId,
                            BreedingDate = request.BreedingDate,
                            DocumentNumber = request.DocumentNumber,
                            SerialNumber = request.SerialNumber,
                            Notes = request.Notes,
                            EITag = a.EITag,
                            EarTag = a.EarTag,
                            BreedingMethod = a.BreedingMethod,
                            EstrusTypeId = a.EstrusTypeId,
                            FirstRating = a.FirstRating,
                            TurnOutBuild = a.TurnOutBuild,
                            TurnOutHuts = a.TurnOutHuts,
                            TransferBuilding = a.TransferBuilding,
                            TransferField = a.TransferField,
                            CreateDate = DateTime.Now,
                            CreateBy = a.CreateBy,
                            ReproductiveState = a.ReproductiveState,
                            Weight = a.Weight,
                            SeedMotherVariety = a.SeedMotherVariety,
                            lastBreedingDate = a.lastBreedingDate,
                            SeedVariety = a.SeedVariety,
                            BreedingRam = a.BreedingRam,
                            BreedState=1,
                        };

                        maternalMatingModes.Add(maternalMatingModel);
                        //修改妊娠状态
                        EditReproductivePresenceState.UpdateReproductivePresenceState(a.EarTag, 1, 7, request.BreedingDate, Gateway);
                        // 批量档案修改状态
                        parms parms = new parms()
                        {
                            earTag = new List<string> { a.EarTag },
                            wanderReproductiveState = 2,
                        };
                        HttpClientHelper.PutDataResponse(Gateway+ "/achs/api/SheepFileModel/WanderStateEditPL", parms);
                        // 批量添加种母历史记录
                        BHpara hpara = new BHpara()
                        {
                            earTag = a.EarTag,
                            breedingDate = a.lastBreedingDate,
                            breedingRam = a.BreedingRam,
                            createBy = a.CreateBy,
                            createDate = DateTime.Now,
                            estrusTypeId = a.EstrusTypeId,
                            seedVariety = a.SeedVariety,
                        };

                        // 创建 BHparaList 对象并添加 hpara 对象
                        BHparaList breedingHistoryModelsList = new BHparaList();
                        breedingHistoryModelsList.breedingHistoryModelsList.Add(hpara);

                        // 调用 HttpClientHelper.PostResponseKey<T>(string, T) 方法，指定 T 为 BHparaList 类型
                        HttpClientHelper.PostResponseKey(Gateway + "/bhset/api/BreedHistory/BatchAddBreedingHistory", breedingHistoryModelsList);
                        // 批量添加转舍记录
                        TransferRecords transfer = new TransferRecords()
                        {
                            EarTag = a.EarTag,
                            SurrenderDate = DateTime.Now,
                            RoundType = 1,
                            TurnOutBuild = 2,
                            TurnOutHuts = 3,
                            TurnOuBuildingManagementId = 2,
                            TurnOuColumnManagementId = 3,
                            ShiftToBuild = 3,
                            ShiftToHuts = 5,
                            ShiftToBuildingManagementId = 3,
                            ShiftToColumnManagementId = 5,
                            Variety = a.SeedMotherVariety,
                            CreateBy= a.CreateBy,
                            CreateDate = DateTime.Now,
                        };
                        Transfer sheep = new Transfer();
                        sheep.sheep.Add(transfer);
                        HttpClientHelper.PostResponseKey(Gateway + "/transfer/api/TransFer/CreateSheepTransFers", sheep);
                    }

                    int rowsAffected = maternalMating.AddMaternalMating(maternalMatingModes);

                    scope.Complete();

                    return rowsAffected;
                }
                catch (Exception ex)
                {
                    // 发生异常时，事务会自动回滚，不需要手动处理
                    // 可以在这里记录日志或执行其他处理

                    throw; // 可以选择抛出异常供调用者处理，或者捕获异常并返回适当的错误信息
                }
            }
        }
        /// <summary>
        /// 修改种母状态
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Handle(UpdateStateCommand request, CancellationToken cancellationToken)
        {
            var models = maternalMating.GetAll().Where(t => t.EarTag == request.Ear).ToList();

            foreach (var item in models)
            {
                item.BreedState = 2;
                maternalMating.Update(item);
            }

            return models.Count; // 返回符合条件的种母对象数量
        }
        /// <summary>
        /// 进行审核
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<bool> Handle(UpdExamineCommand request, CancellationToken cancellationToken)
        {
           var model= maternalMating.GetAll().FirstOrDefault(t=>request.Ids.Contains(t.BreedId.ToString()));
            model.ReviewedDate = DateTime.Now;
            model.ReviewedBy = "江建浩";
            return  maternalMating.Update(model);
        }
        /// <summary>
        /// 修改种母配种信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<bool> Handle(UpdMaternalCommand request, CancellationToken cancellationToken)
        {
            string gateway = configuration.GetValue<string>("Gateway");
           var model= maternalMating.GetAll().FirstOrDefault(t => t.BreedId == request.BreedId);
            model.UserId = request.UserId;
            model.BreedingDate = request.BreedingDate;
            model.DocumentNumber = request.DocumentNumber;
            model.SerialNumber = request.SerialNumber;
            model.Notes = request.Notes;
            model.BreedingMethod = request.BreedingMethod;
            model.EstrusTypeId = request.EstrusTypeId;
            model.FirstRating = request.FirstRating;
            model.TurnOutBuild = request.TurnOutBuild;
            model.TurnOutHuts = request.TurnOutHuts;
            model.TransferBuilding = request.TransferBuilding;
            model.TransferField = request.TransferField;
            model.BreedingRam = request.BreedingRam;
            model.UpdateBy = request.UpdateBy;
            model.UpdateDate = DateTime.Now;
            // 定义并实例化 editBreeds 对象
            editBreeds editBreed = new editBreeds();

            // 设置 EarTag 属性的值
            editBreed.EarTag = request.EarTag;
            //反填种母信息
            var jsonString = HttpClientHelper.PostResponseKey($"{gateway}/bhread/api/BreedingHistoryRead/GetNewBreedingHistoryByPId", editBreed);
            var response = JsonConvert.DeserializeObject<BreedingHistoryDto>(jsonString);

            if (response.PregnancyDate != null)
            {
                return false;
            }
            // 修改种母历史记录
            BHpara hpara = new BHpara()
            {
                BDHRId=response.BDHRId,
                earTag = request.EarTag,
                breedingDate = request.BreedingDate,
                breedingRam = request.BreedingRam,
                updateBy = request.UpdateBy,
                updateDate = DateTime.Now,
                estrusTypeId = request.EstrusTypeId,
                seedVariety = request.SeedVariety,
            };

            // 创建 BHparaList 对象并添加 hpara 对象
            BHparaList breedingHistoryModelsList = new BHparaList();
            breedingHistoryModelsList.breedingHistoryModelsList.Add(hpara);
            HttpClientHelper.PostResponseKey($"{gateway}/bhset/api/BreedHistory/UpdateBreedingHistory", breedingHistoryModelsList);
            var a= maternalMating.Update(model);
            return a;
        }
        /// <summary>
        /// 配种信息删除
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<bool> Handle(DelMaternalCommand request, CancellationToken cancellationToken)
        {
            string authHeader = httpContextAccessor.HttpContext.Request.Headers["Authorization"].FirstOrDefault();
            string gateway = configuration.GetValue<string>("Gateway");
            var items = maternalMating.GetAll();
            var matchingItems = items.Where(x => request.ids.Contains(x.BreedId.ToString())).ToList();
            if (matchingItems.Count() == 0)
            {
                return false;
            }
            try
            {
                 using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    foreach (var item in matchingItems)
                    {
                        // 删除种母配种信息
                        maternalMating.Delete(item.BreedId);
                        //修改妊娠状态
                        EditReproductivePresenceState.UpdateReproductivePresenceState(item.EarTag, 1, 1, item.BreedingDate,gateway);
                        // 批量档案修改状态
                        var parameters = new parms()
                        {
                            earTag = new List<string> { item.EarTag },
                            wanderReproductiveState = 1,
                        };
                         HttpClientHelper.PutDataResponse($"{gateway}/achs/api/SheepFileModel/WanderStateEditPL", parameters);

                        // 定义并实例化 editBreeds 对象
                        editBreeds editBreed = new editBreeds();

                        // 设置 EarTag 属性的值
                        editBreed.EarTag = item.EarTag;
                        //反填种母历史记录
                        var jsonString =  HttpClientHelper.PostResponseKey($"{gateway}/bhread/api/BreedingHistoryRead/GetNewBreedingHistoryByPId", editBreed);
                        var response = JsonConvert.DeserializeObject<BreedingHistoryDto>(jsonString);

                        if (response.PregnancyDate != null)
                        {
                            return false;
                        }

                        // 删除种母历史记录
                        response.IsDel = false; // 不可再编辑
                         HttpClientHelper.PutDataResponse($"{gateway}/bhset/api/BreedHistory/LogicDelBreedingHistory", response);

                        // 删除转舍记录
                         HttpClientHelper.DeleteResponse($"{gateway}/transfer/api/TransFer/DeleteSheepTransFer?EarTag={item.EarTag}&CreateBy={item.CreateBy}");
                    }

                    // 提交事务
                    scope.Complete();
                }

                return true;
            }
            catch (Exception ex)
            {
                // 处理异常情况
                // 输出异常信息或写入日志
                Console.WriteLine($"An error occurred: {ex.Message}");

                return false;
            }
        }
        /// <summary>
        /// 修改回状态（妊检删除使用）
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Handle(UpdateHuiStateCommand request, CancellationToken cancellationToken)
        {
            var models = maternalMating.GetAll().Where(t => t.EarTag == request.Ear).ToList();

            foreach (var item in models)
            {
                item.BreedState = 1;
                maternalMating.Update(item);
            }

            return models.Count; // 返回符合条件的种母对象数量
        }

        public editBreeds editBreed { get; set; }

        public class editBreeds
        {

            public string EarTag { get; set; }
        }
        //添加种母历史记录
        public class BHparaList
        {
            public List<BHpara> breedingHistoryModelsList { get; set; }

            public BHparaList()
            {
                breedingHistoryModelsList = new List<BHpara>();
            }
        }
        //转舍添加
        public class Transfer
        {
            public List<TransferRecords> sheep { get; set; }

            public Transfer()
            {
                sheep = new List<TransferRecords>();
            }
        }
        //批量修改状态
        public class parms 
        {
            public List<string> earTag { get; set; }

            public int wanderReproductiveState { get; set; }
        }

        //添加种母历史记录
        public class BHpara
        {
            public int BDHRId { get; set; }
            /// <summary>
            /// 种母电子耳标
            /// </summary>
            [Column(TypeName = "nvarchar(50)")]
            [MaxLength(50)]
            public string? earTag { get; set; }
            /// <summary>
            /// 配种日期
            /// </summary>
            public DateTime? breedingDate { get; set; }
            /// <summary>
            /// 种公电子耳号
            /// </summary>
            [Column(TypeName = "nvarchar(50)")]
            [MaxLength(50)]
            public string? breedingRam { get; set; }
            /// <summary>
            /// 妊检日期
            /// </summary>
            public DateTime? pregnancyDate { get; set; }
            /// <summary>
            /// 妊检结果
            /// </summary>
            public int pregnancytestResult { get; set; }
            /// <summary>
            /// 分娩日期
            /// </summary>
            public DateTime? deliveryDate { get; set; }
            /// <summary>
            /// 健羔数
            /// </summary>
            public int healthyNumber { get; set; }
            /// <summary>
            /// 健羔总重
            /// </summary>
            public decimal totalWeightOfHealthyLambs { get; set; }
            /// <summary>
            /// 弱羔数
            /// </summary>
            public int lambNumber { get; set; }
            /// <summary>
            /// 畸形数
            /// </summary>
            public int deformityNumber { get; set; }
            /// <summary>
            /// 死胎数
            /// </summary>
            public int stillbirthsNumber { get; set; }
            /// <summary>
            /// 木乃伊数
            /// </summary>
            public int mummyNumber { get; set; }
            /// <summary>
            /// 畸胎数
            /// </summary>
            public int freaksNumber { get; set; }
            /// <summary>
            /// 当前胎次
            /// </summary>
            public int currentPregnancy { get; set; }
            /// <summary>
            /// 断奶日期
            /// </summary>
            public DateTime? weaningDate { get; set; }
            /// <summary>
            /// 断奶只数
            /// </summary>
            public int weaningCount { get; set; }
            /// <summary>
            /// 断奶窝重
            /// </summary>
            public decimal totalweaningWeightg { get; set; }
            /// <summary>
            /// 创建人
            /// </summary>
            public string? createBy { get; set; }
            /// <summary>
            /// 创建日期
            /// </summary>
            public DateTime? createDate { get; set; }
            /// <summary>
            /// 修改人
            /// </summary>
            public string? updateBy { get; set; }
            /// <summary>
            /// 修改日期
            /// </summary>
            public DateTime? updateDate { get; set; }
            /// <summary>
            /// 逻辑删除标志
            /// </summary>
            public bool isDel { get; set; }
            /// <summary>
            /// 是否可编辑（默认可编辑）
            /// </summary>
            public bool isEditor { get; set; } = true;
            /// <summary>
            /// 种母发情类型
            /// </summary>
            public int? estrusTypeId { get; set; }

            /// <summary>
            /// 种公品种
            /// </summary>
            public string? seedVariety { get; set; }
        }
        //批量添加转舍记录
        public class TransferRecords
        {
            /// <summary>
            /// 转舍主键，自增标识列
            /// </summary>
            public int SheepRescissionId { get; set; }
            /// <summary>
            /// 可视耳标
            /// </summary>
            public string? EarTag { get; set; }
            /// <summary>
            /// 转舍日期
            /// </summary>
            public DateTime? SurrenderDate { get; set; }
            /// <summary>
            /// 转舍类型
            /// </summary>
            public int RoundType { get; set; }
            /// <summary>
            /// 转出栋舍
            /// </summary>
            public int TurnOutBuild { get; set; }

            /// <summary>
            /// 转出栏位
            /// </summary>
            public int TurnOutHuts { get; set; }
            /// <summary>
            /// 转出栋舍主键
            /// </summary>
            public int TurnOuBuildingManagementId { get; set; }
            /// <summary>
            /// 转出栏位主键
            /// </summary>
            public int TurnOuColumnManagementId { get; set; }
            /// <summary>
            /// 转入栋舍
            /// </summary>
            public int ShiftToBuild { get; set; }
            /// <summary>
            /// 转入栏位
            /// </summary>
            public int ShiftToHuts { get; set; }
            /// <summary>
            /// 转入栋舍主键
            /// </summary>
            public int ShiftToBuildingManagementId { get; set; }
            /// <summary>
            /// 转入栏位主键
            /// </summary>
            public int ShiftToColumnManagementId { get; set; }
            /// <summary>
            /// 品种
            /// </summary>
            public string? Variety { get; set; }
            /// <summary>
            /// 创建人
            /// </summary>
            [Column(TypeName = "nvarchar(20)")]
            [MaxLength(20)]
            public string? CreateBy { get; set; }

            /// <summary>
            /// 创建时间
            /// </summary>
            public DateTime? CreateDate { get; set; }

            /// <summary>
            /// 修改人
            /// </summary>
            [Column(TypeName = "nvarchar(20)")]
            [MaxLength(20)]
            public string? UpdateBy { get; set; }

            /// <summary>
            /// 修改时间
            /// </summary>
            public DateTime? UpdateDate { get; set; }
            /// <summary>
            /// 是否删除
            /// </summary>
            public bool IsDel { get; set; }
            /// <summary>
            /// 单据号
            /// </summary>
            public long DocumentNumbe { get; set; }
            /// <summary>
            /// 羊只类型
            /// </summary>
            public string? Type { get; set; }
        }
    }
}
